package cn.jwcat.service.impl;

import cn.jwcat.entity.File;
import cn.jwcat.mapper.StaffMapper;
import cn.jwcat.service.IFileService;
import cn.jwcat.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@Transactional
@Service
public class FileServiceImpl implements IFileService {

	@Resource
	JwtTokenUtil jwtTokenUtil;
	@Resource
	StaffMapper staffMapper;

	@Value("${image.localUrlPath}")
	private String localUrlPath;

	@Override
	public File upload(MultipartFile file) throws IOException {
		String fileName = file.getOriginalFilename();
		String typeName = file.getContentType();
		String typePath = "/" + typeName + "/";
		String localDir = localUrlPath + typePath;
		java.io.File dirFile = new java.io.File(localDir);
		if (!dirFile.exists()) {
			boolean mkdirs = dirFile.mkdirs();
		}
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fileType = null;
		if (fileName != null) {
			fileType = fileName.substring(fileName.lastIndexOf("."));
		}
		String realFileName = uuid + fileType;
		String filePathAll = localDir + realFileName;
		System.out.println(filePathAll);
		java.io.File realFile = new java.io.File(filePathAll);
		file.transferTo(realFile);
		String virtualPath = typePath + realFileName;
		System.out.println(virtualPath);
		return new File(virtualPath, realFileName);
	}
}

